using Catastrophe.BasePC.UI.DbDal;
using Catastrophe.BasePC.UI.Model;
using Catastrophe.BasePC.UI.SystemIni;
using SqlSugar;
using SqlSugarEx;
using SqlSugarEx.Utilities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Reflection;

namespace Catastrophe.BasePC.UI.DbDal
{
    public class SysMenuDal
    {
        private readonly SqlSugarClientEx _dbSugar;

        public SysMenuDal()
        {
            _dbSugar = DbUtility.GetSugar(Catastrophe.Initialize.SystemIni.FileConfigIni.GetDbAppConfig, isAutoCloseCon: true);
        }

        public DataTable QueryBaseMenuNodeBind(string nodeName)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            DataTable result = _dbSugar.QueryableBind<SysMenuEntity>().WhereIF(!string.IsNullOrWhiteSpace(nodeName), (x) => x.NodeName.Contains(nodeName)).OrderBy("base_index ASC")
                .ToDataTable();
            stopwatch.Stop();
            long elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
            return result;
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="nodeName"></param>
        /// <returns></returns>
        public List<SysMenuEntity> QueryBaseMenuNodeList(string nodeName)
        {
            return _dbSugar.QueryableBind<SysMenuEntity>().
                   WhereIF(!string.IsNullOrWhiteSpace(nodeName), (x) => x.NodeName.Contains(nodeName)).
                   OrderBy("base_index ASC").ToList();

        }
        public int UpdateSoftId(int id, string value)
        {
            return _dbSugar.Updateable(new SysMenuEntity
            {
                Id = id,
                SoftId = value
            }).UpdateColumns((x) => new { x.SoftId }).ExecuteCommand();
        }

        public List<SysMenuEntity> QueryBaseMenuNode(string userName = "", string userNo = "", string depart = "", string identity = "", string authorizeType = "", bool isAdmin = false)
        {
            if (string.IsNullOrWhiteSpace(userName) && string.IsNullOrWhiteSpace(userNo) && string.IsNullOrWhiteSpace(depart) && string.IsNullOrWhiteSpace(authorizeType) && string.IsNullOrWhiteSpace(identity))
            {
                return _dbSugar.Queryable<SysMenuEntity>().Where(x => x.Visible).ToList();
                //return (from x in _dbSugar.Queryable<SysMenuEntity>()
                //        where x.Visible
                //        select x).ToList();
            }
            List<SysMenuEntity> list = new List<SysMenuEntity>();
            List<MenuUnionEntity> userMenuRights = new SysRoleMenuDal().GetUserMenuRights(userName, userNo, depart, identity, authorizeType, queryMenuOnly: true);
            foreach (MenuUnionEntity item in userMenuRights)
            {
                SysMenuEntity sysMenuEntity = new SysMenuEntity
                {
                    Id = item.MenuId,
                    BaseIndex = item.BaseIndex,
                    ParentIndex = item.ParentIndex,
                    NodeName = item.NodeName,
                    Visible = item.NodeState,
                    IsFixed = item.IsFixed,
                    FormType = item.FormType,
                    LoadMode = item.LoadMode,
                    InstanceLife = item.InstanceLife,
                    QuickAccess = item.QuickAccess,
                    QaBtnIndex = item.QaBtnIndex,
                    QuickAccessKey = item.QuickAccessKey,
                    FixedFrmIndex = item.FixedFrmIndex,
                    Assembly = item.Assembly,
                    ResourceName = item.NameSpace,
                    WndChild = item.WndChild,
                    LoadProgFullName = item.LoadProgFullName,
                    WndChildCaption = item.WndChildCaption,
                    LoadFrmSize = item.LoadFrmSize,
                    BeforeShowMethod = item.BeforeShowMethod,
                    SoftId = item.SoftId
                };
                if ((sysMenuEntity.NodeName == "用户管理" || sysMenuEntity.NodeName == "角色管理" || sysMenuEntity.NodeName == "权限模板") && isAdmin)
                {
                    sysMenuEntity.Visible = true;
                }
                list.Add(sysMenuEntity);
            }
            return list;
        }

        public bool UpdateBind()
        {
            return _dbSugar.UpdateBind();
        }

        public void Clear(List<string> assemblyBuff)
        {
            SqlSugarClientEx sugar = DbUtility.GetSugar(Catastrophe.Initialize.SystemIni.FileConfigIni.GetDbAppConfig, isAutoCloseCon: true);
            try
            {
                sugar.BeginTran();
                List<int> deletePkBuff = (from x in sugar.Queryable<SysMenuEntity>()
                                          where !SqlFunc.ContainsArray(assemblyBuff.ToArray(), x.Assembly) && !SqlFunc.IsNullOrEmpty(x.Assembly) || SqlFunc.IsNullOrEmpty(x.Assembly) && SqlFunc.IsNullOrEmpty(x.WndChildCaption) && x.ParentIndex != -1 || SqlFunc.IsNullOrEmpty(x.BaseIndex) || SqlFunc.IsNullOrEmpty(x.NodeName)
                                          select x.Id).ToList();
                if (deletePkBuff.Count > 0)
                {
                    sugar.Deleteable<SysMenuEntity>(deletePkBuff).ExecuteCommand();
                    (from x in sugar.Deleteable<SysRoleMenuEntity>()
                     where SqlFunc.ContainsArray(deletePkBuff, x.MenuId)
                     select x).ExecuteCommand();
                }
                sugar.CommitTran();
            }
            catch (Exception)
            {
                sugar.RollbackTran();
            }
        }

        /// <summary>
        /// 查询资源地址
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public SysMenuEntity QueryBaseResourceName(string? obj)
        {
            return _dbSugar.Queryable<SysMenuEntity>().Where(x => x.ResourceName == obj).First();
        }

        /// <summary>
        /// 数据编辑
        /// </summary>
        /// <param name="dataId"></param>
        /// <param name="name"></param>
        /// <param name="instance_life"></param>
        /// <returns></returns>
        public int UpdateData(SysMenuEntity entity)
        {
            return _dbSugar.Updateable<SysMenuEntity>().
                 SetColumns(x => new SysMenuEntity()
                 {
                     NodeName = entity.NodeName,
                     Assembly = entity.Assembly,
                     BaseIndex = entity.BaseIndex,
                     InstanceLife = entity.InstanceLife,
                     IsFixed = entity.IsFixed,
                     ParentIndex = entity.ParentIndex,
                     TimeStamp = entity.TimeStamp,
                     Visible = entity.Visible,
                     ResourceName = entity.ResourceName,
                     SoftId = entity.SoftId,

                 }).Where(x => x.Id == entity.Id).ExecuteCommand();
        }

        public void AddData(SysMenuEntity newentity)
        {
            _dbSugar.Insertable(newentity).ExecuteCommand();
        }
        /// <summary>
        /// 查询数量
        /// </summary>
        /// <param name="baseIndex"></param>
        /// <returns></returns>
        public int QueryDataByIndex(int baseIndex)
        {
            return _dbSugar.Queryable<SysMenuEntity>().Where(x => x.BaseIndex == baseIndex).Count();
        }

        public void DeleteData(int id)
        {
            _dbSugar.Deleteable<SysMenuEntity>().Where(x => x.Id == id).ExecuteCommand();
        }

        /// <summary>
        /// 查询菜单
        /// </summary>
        /// <returns></returns>
        public List<SysMenuEntity> QueryMenuNode()
        {
            return _dbSugar.Queryable<SysMenuEntity>().ToList();
        }
    }
}
